package app.controller.wechat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.scyf.weixintool.WeiXinServerVerifier;

import app.utils.DataResponse;

@Controller
public class WeChatCheckerController {
	@Resource(name="callbackwx")
	private EventHandle eventHandle;
	@RequestMapping(value="/wechat" ,method={RequestMethod.GET,RequestMethod.POST})
	public void weChatMenuBulider(HttpServletRequest request, String signature,String timestamp,String nonce,String echostr, HttpServletResponse response) throws IOException{
		if (validate(echostr)) {
			if (validate(signature, timestamp, nonce)) {
				if (WeiXinServerVerifier.verifyRequest(signature, "curiousxeon", timestamp, nonce)) {
				//if (WeiXinServerVerifier.verifyRequest(signature, "654258Tj", timestamp, nonce)) {
					PrintWriter writer = response.getWriter();
					writer.append(echostr);
					writer.flush();
					
					return;
				} else {
					DataResponse.jsonResponse(response, -1);
					return;
				}
			} else {
				DataResponse.jsonResponse(response, -1);
				return;
			} 
		}else {
			request.setCharacterEncoding("utf-8");
			ServletInputStream xml = request.getInputStream();
			StringBuilder xmlBuilder=new StringBuilder();
			BufferedReader reader=new BufferedReader(new InputStreamReader(xml,"UTF-8"));
			String buff;
			while((buff=reader.readLine())!=null){
				xmlBuilder.append(buff);
			}
			if (xmlBuilder!=null&&!"".equals(xmlBuilder.toString())) {
				eventHandle.Handle(response, xmlBuilder.toString());
				return;
			}
			DataResponse.jsonResponse(response, "no xml file !!!");
			return;
		}
	}
	
	
	//服务器数据校验
	private boolean validate(String ... val ){
		if (val!=null && val.length>0) {
			for(String str:val){
				if (str==null||"".equals(str)) {
					return false;
				}
			}
			return true;
		}
		return false;
	}
	
}
